import api from '../../utils/api';
import util from '../../utils/common';
import { QueryType, ArticleType } from '../../types/index';

Page({
  data: {
    isShow: false,
    placeholder: '写点评论',
    postId: '',
    parentId: 0,
    comments: [],
    info: {},
    currentComment: {},
    loading: true
  },
  onLoad(query: QueryType) {
    this.getDetail(query.id);
    this.getComment(query.id);
    this.setData({
      postId: query.id
    })
  },
  // 获取文章详情
  async getDetail (id) {
    const res: ArticleType = await api.getArticlebyID(id);
    if (res) {
      res.date = res.date && util.transformDate(res.date);    
      res.content.rendered = util.handleArticleImg(res.content.rendered);
      this.setData({
        info: res,
        loading: false
      })
    }
  },
  // 获取当前文章评论
  async getComment (id) {
    const res = await api.getComments({post: id});
    if (res && Array.isArray(res)) {
      const data = util.organizeComments(res);
      this.setData({
        comments: data,
        loading: false
      })
    }
  },
  // 回复评论
  handleReplyComments (e) {
    const name = e.info.author_name;
    this.setData({
      placeholder: `@${name}`,
      isShow: true,
      postId: e.info.post,
      parentId: e.info.id
    })
  },
  // 发布评论
  async handleAddComment(params) {
    const res = await api.addComments({
      content: params.content,
      post: this.data.postId,
      author: params.author,
      parent: this.data.parentId
    });
    if (res) {
      const that = this;
      my.showToast({
        content: '评论审核中，审核通过之后即可阅览',
        type: 'none',
        duration: 2000,
        success: () => {
          that.getComment(that.data.postId);
          that.setData({
            isShow: false
          })
        }
      })
    }
  },
  // 打开评论弹层
  onClickComment() {
    this.setData({
      isShow: true,
      placeholder: '写点评论...',
      parentId: 0
    })
  },
  handleClosePopup() {
    this.setData({
      isShow: false
    })
  }
});
